package cn.java79.quiz.web;

import cn.java79.quiz.entity.Admin;
import cn.java79.quiz.pojo.AjaxPage;
import cn.java79.quiz.pojo.AjaxResult;
import cn.java79.quiz.service.AdminService;
import cn.java79.quiz.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @author oldliu
 * @since 1.0
 */
@WebServlet("*.do")//不需要/
public class AdminServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String path = req.getServletPath();
        path = path.substring(1, path.length() - 3);
        try {
            Method m = this.getClass().getDeclaredMethod(path, HttpServletResponse.class, HttpServletRequest.class);
            m.invoke(this,resp,req);
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(501,"服务器出现了错误"+e);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);//get和post行为一致
    }
    //    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("text/html;charset=utf-8");
//        PrintWriter writer = resp.getWriter();//out对应
//        writer.write("<!DOCTYPE html>");
//        writer.write("<html>");
//        writer.write("<body>");
//        writer.write("<h2>contextpath:" + req.getContextPath() + "</h2>");
//        writer.write("<h2>url:" + req.getRequestURL() + "</h2>");
//        writer.write("<h2>URI:" + req.getRequestURI() + "</h2>");
//        writer.write("<h2>请求地址:" + req.getServletPath() + "</h2>");
//        String path = req.getServletPath();
//        path = path.substring(1, path.length() - 3);
//        if (path.equals("login")) {
//            writer.println("<h1>这是登录操作</h1>");
//            login(resp, req);
//        } else if (path.equals("update")) {
//            writer.println("<h1>这是修改操作</h1>");
//            update(resp, req);
//        } else if (path.equals("delete")) {
//            writer.println("<h1>这是删除操作</h1>");
//        } else {
//            writer.println("<h1>这是unkown操作</h1>");
//        }
//        writer.write("</body>");
//        writer.write("</html>");
//    }

    public void login(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String login = request.getParameter("login");
        String pass = request.getParameter("pass");
        Admin admin = AdminService.ME.login(login, pass);
        if (admin != null) {
            HttpSession session = request.getSession();//内置的session
            //request.getServletContext()//application
            session.setAttribute("USER_LOGIN", admin);
            response.sendRedirect("main.jsp");//重定向
            //response.sendRedirect("users.jsp");//重定向
            //request.getRequestDispatcher("users.jsp").forward(request,response);//转发
            return;
        }
        response.getWriter().println("登录失败");
    }

    public void update(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        response.getWriter().println("这是修改");
    }

    public void delete(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        //response.getWriter().println("这是删除");
        Long id=StrUtil.toLong(request.getParameter("id"));
        int r=AdminService.ME.del(id);
        AjaxResult result=r>0?AjaxResult.success():AjaxResult.error("删除失败");
        response.setContentType("application/json;charset=utf-8");
        //发送给前端
        response.getWriter().print(JSON.toJSONString(result));
    }

    public void search(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        String login = request.getParameter("loginname");
        String realname = request.getParameter("realname");

        int pageNo = StrUtil.toInt(request.getParameter("pageNo"), 1);
        AjaxPage<Admin> page = AdminService.ME.search(login, realname, pageNo);
        //用fastjson转换对象成字符串
        //null的处理，日期的处理
        String sb = JSON.toJSONString(page,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNonStringValueAsString,
                SerializerFeature.UseISO8601DateFormat);

        //拼装成一个json格式的字符串
//        StringBuilder sb=new StringBuilder();
//        //拼接字符串，留意json的格式
//        sb.append("{");
//        sb.append("\"count\":");
//        sb.append(page.getCount());
//        sb.append(",\"page\":"+page.getPage());
//        sb.append(",\"pageNums\":"+page.getPageNums());
//        sb.append(",\"pageSize\":"+page.getPageSize());
//        sb.append(",");
//        sb.append("\"data\":[");
//        for(int i=0;i<page.getData().size();i++){
//            Admin admin=page.getData().get(i);
//            sb.append("{");
//            sb.append("\"id\":"+admin.getId());
//            sb.append(",\"loginname\":\""+admin.getLoginname()+"\"");
//            sb.append(",\"realname\":\""+admin.getRealname()+"\"");
//            sb.append(",\"email\":\""+admin.getEmail()+"\"");
//            sb.append("}");
//            if(i<page.getData().size()-1){
//                sb.append(",");
//            }
//        }
//        sb.append("]");
//        sb.append("}");
        //设置json格式的请求头
        response.setContentType("application/json;charset=utf-8");
        //发送给前端
        response.getWriter().print(sb);
    }

}
